import React, { useState, useEffect } from "react";
import Robot from "../../components/Robot";
import RobotDiscount from "../../components/RobotDiscount";
import ShoppingCart from "../../components/ShoppingCart";
import {
  Container,
  AppHeader,
  RobotList,
  Loading,
  AppLogo,
  Title,
} from "./style";

const Home: React.FC = (props) => {
  const [robotGallery, setRobotGallery] = useState<any>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string>();

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        const responses = await fetch(
          "https://jsonplaceholder.typicode.com/users"
        );
        // .then(response => response.json())
        // .then(data => setRobotGallery(data))
        const data = await responses.json();
        setRobotGallery(data);
      } catch (e: any) {
        setError(e.message);
      }
      setLoading(false);
    };

    fetchData();
  }, []);

  return (
    <Container>
      <AppHeader>
        <AppLogo />
        <Title>罗伯特机器人炫酷online购物平台</Title>
      </AppHeader>
      <ShoppingCart />
      {(!error || error !== "") && <div>{error}</div>}
      {!loading ? (
        <RobotList>
          {robotGallery.map(
            (r: { id: number; email: string; name: string }, index: number) =>
              index % 2 === 0 ? (
                <RobotDiscount id={r.id} email={r.email} name={r.name} />
              ) : (
                <Robot id={r.id} email={r.email} name={r.name} />
              )
          )}
        </RobotList>
      ) : (
        <Loading>loading 加载中</Loading>
      )}
    </Container>
  );
};

export default Home;
